//
//  YZStringPickerView.m
//  VET
//
//  Created by 刘文靖 on 2018/6/28.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZStringPickerView.h"

@interface YZStringPickerViewCell :UITableViewCell
@property (nonatomic, strong) UILabel *stringLabel;
@end

@implementation YZStringPickerViewCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(nullable NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // UI
        [self setupUI];
    }
    return self;
}

- (void)setupUI{
    self.stringLabel = [[UILabel alloc] init];
    self.stringLabel.textColor = kColorWithHex(0x007AFF);
    self.stringLabel.font = [UIFont fontWithName:@"SFProDisplay-Regular" size:20];
    self.stringLabel.frame = CGRectMake(0, 16, self.frame.size.width, 28);
    self.stringLabel.textAlignment = NSTextAlignmentCenter;
    [self.contentView addSubview:self.stringLabel];
}
@end

typedef NS_ENUM(NSInteger, YZStringPickerMode) {
    YZStringPickerComponentSingle,  // 单列
    YZStringPickerComponentMore     // 多列
};
#define kStringPickerViewHeight MIN(kScreenHeight - 203,465)
@interface YZStringPickerView ()<UITableViewDelegate,UITableViewDataSource>
{
    BOOL isDataSourceValid; // 数据源是否合法
}
// 字符串TableView
@property (nonatomic, strong) UITableView *pickerView;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, assign) YZStringPickerMode type;
@property (nonatomic, strong) NSArray *dataSourceArr;
// 单列选择的值
@property (nonatomic, strong) NSString *selectValue;
// 多列选择的值
@property (nonatomic, strong) NSMutableArray *selectValueArr;

// 是否开启自动选择
@property (nonatomic, assign) BOOL isAutoSelect;
// 主题色
@property (nonatomic, strong) UIColor *themeColor;
@property (nonatomic, copy) YZStringResultBlock resultBlock;
@property (nonatomic, copy) YZStringCancelBlock cancelBlock;

@end
@implementation YZStringPickerView

#pragma mark - 1.显示自定义字符串选择器
+ (void)showStringPickerWithTitle:(NSString *)title
                       dataSource:(id)dataSource
                  defaultSelValue:(id)defaultSelValue
                      resultBlock:(YZStringResultBlock)resultBlock {
    [self showStringPickerWithTitle:title dataSource:dataSource defaultSelValue:defaultSelValue isAutoSelect:NO themeColor:nil resultBlock:resultBlock cancelBlock:nil];
}

#pragma mark - 2.显示自定义字符串选择器（支持 设置自动选择 和 自定义主题颜色）
+ (void)showStringPickerWithTitle:(NSString *)title
                       dataSource:(id)dataSource
                  defaultSelValue:(id)defaultSelValue
                     isAutoSelect:(BOOL)isAutoSelect
                       themeColor:(UIColor *)themeColor
                      resultBlock:(YZStringResultBlock)resultBlock {
    [self showStringPickerWithTitle:title dataSource:dataSource defaultSelValue:defaultSelValue isAutoSelect:isAutoSelect themeColor:themeColor resultBlock:resultBlock cancelBlock:nil];
}

#pragma mark - 3.显示自定义字符串选择器（支持 设置自动选择、自定义主题颜色、取消选择的回调）
+ (void)showStringPickerWithTitle:(NSString *)title
                       dataSource:(id)dataSource
                  defaultSelValue:(id)defaultSelValue
                     isAutoSelect:(BOOL)isAutoSelect
                       themeColor:(UIColor *)themeColor
                      resultBlock:(YZStringResultBlock)resultBlock
                      cancelBlock:(YZStringCancelBlock)cancelBlock {
    YZStringPickerView *strPickerView = [[YZStringPickerView alloc]initWithTitle:title dataSource:dataSource defaultSelValue:defaultSelValue isAutoSelect:isAutoSelect themeColor:themeColor resultBlock:resultBlock cancelBlock:cancelBlock];
    NSAssert(strPickerView->isDataSourceValid, @"数据源不合法！请检查字符串选择器数据源的格式");
    if (strPickerView->isDataSourceValid) {
        [strPickerView showWithAnimation:YES];
    }
}

#pragma mark - 初始化自定义字符串选择器
- (instancetype)initWithTitle:(NSString *)title
                   dataSource:(id)dataSource
              defaultSelValue:(id)defaultSelValue
                 isAutoSelect:(BOOL)isAutoSelect
                   themeColor:(UIColor *)themeColor
                  resultBlock:(YZStringResultBlock)resultBlock
                  cancelBlock:(YZStringCancelBlock)cancelBlock {
    if (self = [super init]) {
        self.title = title;
        self.isAutoSelect = isAutoSelect;
        self.themeColor = themeColor;
        self.resultBlock = resultBlock;
        self.cancelBlock = cancelBlock;
        isDataSourceValid = YES;
        [self configDataSource:dataSource defaultSelValue:defaultSelValue];
        if (isDataSourceValid) {
            [self initUI];
        }
    }
    return self;
}

#pragma mark - 设置数据源
- (void)configDataSource:(id)dataSource defaultSelValue:(id)defaultSelValue {
    // 1.先判断传入的数据源是否合法
    if (!dataSource) {
        isDataSourceValid = NO;
    }
    NSArray *dataArr = nil;
    if ([dataSource isKindOfClass:[NSArray class]] && [dataSource count] > 0) {
        dataArr = [NSArray arrayWithArray:dataSource];
    } else if ([dataSource isKindOfClass:[NSString class]] && [dataSource length] > 0) {
        NSString *plistName = dataSource;
        NSString *path = [[NSBundle mainBundle] pathForResource:plistName ofType:nil];
        dataArr = [[NSArray alloc] initWithContentsOfFile:path];
        if (!dataArr || dataArr.count == 0) {
            isDataSourceValid = NO;
        }
    } else {
        isDataSourceValid = NO;
    }
    // 判断数组是否合法（即数组的所有元素是否是同一种数据类型）
    if (isDataSourceValid) {
        Class itemClass = [[dataArr firstObject] class];
        for (id obj in dataArr) {
            if (![obj isKindOfClass:itemClass]) {
                isDataSourceValid = NO;
                break;
            }
        }
    }
    if (!isDataSourceValid) {
        return;
    }
    // 2. 给数据源赋值
    self.dataSourceArr = dataArr;
    
    // 3. 根据数据源 数组元素的类型，判断选择器的显示类型
    if ([[self.dataSourceArr firstObject] isKindOfClass:[NSString class]]) {
        self.type = YZStringPickerComponentSingle;
    } else if ([[self.dataSourceArr firstObject] isKindOfClass:[NSArray class]]) {
        self.type = YZStringPickerComponentMore;
    }
    // 4. 给选择器设置默认值
    if (self.type == YZStringPickerComponentSingle) {
        if (defaultSelValue && [defaultSelValue isKindOfClass:[NSString class]] && [defaultSelValue length] > 0 && [self.dataSourceArr containsObject:defaultSelValue]) {
            self.selectValue = defaultSelValue;
        } else {
            self.selectValue = [self.dataSourceArr firstObject];
        }
        NSInteger row = [self.dataSourceArr indexOfObject:self.selectValue];
        // 默认滚动的行
        [self.pickerView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    } else if (self.type == YZStringPickerComponentMore) {
        NSMutableArray *tempArr = [NSMutableArray array];
        for (NSInteger i = 0; i < self.dataSourceArr.count; i++) {
            NSString *selValue = nil;
            if (defaultSelValue && [defaultSelValue isKindOfClass:[NSArray class]] && [defaultSelValue count] > 0 && i < [defaultSelValue count] && [self.dataSourceArr[i] containsObject:defaultSelValue[i]]) {
                [tempArr addObject:defaultSelValue[i]];
                selValue = defaultSelValue[i];
            } else {
                [tempArr addObject:[self.dataSourceArr[i] firstObject]];
                selValue = [self.dataSourceArr[i] firstObject];
            }
            NSInteger row = [self.dataSourceArr[i] indexOfObject:selValue];
            // 默认滚动的行
            [self.pickerView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
        }
        self.selectValueArr = [tempArr copy];
    }
}

#pragma mark - 初始化子视图
- (void)initUI {
    self.frame = kScreenBounds;
    // 设置子视图的宽度随着父视图变化
    self.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    // 背景遮罩图层
    [self addSubview:self.backgroundView];
    // 弹出视图
    [self addSubview:self.alertView];
    self.alertView.frame = CGRectMake(10, kScreenHeight - kStringPickerViewHeight, kScreenWidth -20, kStringPickerViewHeight);
    self.alertView.backgroundColor = [UIColor clearColor] ;
    // 设置弹出视图子视图
    UIView *topInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.alertView.frame.size.width, kStringPickerViewHeight - 76)];
    topInfoView.layer.cornerRadius = 13;
    topInfoView.layer.masksToBounds = YES;
    [self.alertView addSubview:topInfoView];
    // 添加顶部标题栏
    [topInfoView addSubview:self.topView];
    self.topView.frame = CGRectMake(0, 0, self.alertView.frame.size.width, 45);
    // 添加中间标题按钮
    [topInfoView addSubview:self.titleLabel];
    self.titleLabel.font = [UIFont systemFontOfSize:13.0f * kScaleFit];
    self.titleLabel.textColor = kColorWithHex(0x8F8E94);
    // 添加分割线
    [topInfoView addSubview:self.lineView];
    //self.lineView.backgroundColor = kColorWithHexAlpha(0x4D4D4D, 0.78);
    self.titleLabel.text = self.title;
    // 添加字符串选择器
    [topInfoView addSubview:self.pickerView];
    
    UIButton *cancelButton = [[UIButton alloc] init];
    cancelButton.backgroundColor = [UIColor whiteColor];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:kColorWithHexAlpha(0x007AFF, 1.0) forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont fontWithName:@"SFProDisplay-Semibold" size:20];
    cancelButton.frame = CGRectMake(0, self.alertView.frame.size.height - 66, self.alertView.frame.size.width, 57);
    cancelButton.layer.cornerRadius = 13;
    [cancelButton addTarget:self action:@selector(clickLeftBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.alertView addSubview:cancelButton];
    if (self.themeColor && [self.themeColor isKindOfClass:[UIColor class]]) {
        [self setupThemeColor:self.themeColor];
    }
}


#pragma mark - 字符串选择器
- (UITableView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopViewHeight + 1, kScreenWidth -20, kStringPickerViewHeight - 122)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        // 设置子视图的大小随着父视图变化
        _pickerView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
        _pickerView.alwaysBounceVertical = NO;
        _pickerView.rowHeight = 57;
        [_pickerView registerClass:[YZStringPickerViewCell class] forCellReuseIdentifier:@"YZStringPickerViewCell"];
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
    }
    return _pickerView;
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YZStringPickerViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YZStringPickerViewCell"];
    cell.stringLabel.text = self.dataSourceArr[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.selectValue = self.dataSourceArr[indexPath.row];
    if(self.resultBlock) {
        self.resultBlock(self.selectValue);
    }

}

#pragma mark - 背景视图的点击事件
- (void)didTapBackgroundView:(UITapGestureRecognizer *)sender {
    [self dismissWithAnimation:NO];
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

#pragma mark - 取消按钮的点击事件
- (void)clickLeftBtn {
    [self dismissWithAnimation:YES];
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

#pragma mark - 确定按钮的点击事件
- (void)clickRightBtn {
    [self dismissWithAnimation:YES];
    // 点击确定按钮后，执行block回调
    if(_resultBlock) {
        if (self.type == YZStringPickerComponentSingle) {
            _resultBlock(self.selectValue);
        } else if (self.type == YZStringPickerComponentMore) {
            _resultBlock(self.selectValueArr);
        }
    }
}

#pragma mark - 弹出视图方法
- (void)showWithAnimation:(BOOL)animation {
    //1. 获取当前应用的主窗口
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    [keyWindow addSubview:self];
    if (animation) {
        // 动画前初始位置
        CGRect rect = self.alertView.frame;
        rect.origin.y = kScreenHeight;
        self.alertView.frame = rect;
        // 浮现动画
        [UIView animateWithDuration:0.3 animations:^{
            CGRect rect = self.alertView.frame;
            rect.origin.y -= kStringPickerViewHeight;
            self.alertView.frame = rect;
        }];
    }
}

#pragma mark - 关闭视图方法
- (void)dismissWithAnimation:(BOOL)animation {
    // 关闭动画
    [UIView animateWithDuration:0.2 animations:^{
        CGRect rect = self.alertView.frame;
        rect.origin.y += kStringPickerViewHeight;
        self.alertView.frame = rect;
        self.backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (NSArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSArray array];
    }
    return _dataSourceArr;
}

- (NSMutableArray *)selectValueArr {
    if (!_selectValueArr) {
        _selectValueArr = [[NSMutableArray alloc]init];
    }
    return _selectValueArr;
}

@end
